<?php

namespace App\Http\Controllers\Back;

use App\Models\Back\Setting;
use App\Tool\Tool;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class SettingController extends Controller
{
	/*
	 * 设置
	 * get请求显示页面
	 * post请求修改配置信息
	 */
	public function set (Request $request)
	{
		//实例化模型
		$Model = new Setting();

		//表单验证
		$Model->setValidator($request->all());

		//更新数据库
		$res = $Model->set($request->all());

		if ($res) {
			//删除缓存
			Cache::forget('settingGroupList');
			return redirect()->route('setting.list');
		} else {
			return back()->withInput();
		}
	}

	/*
	 * ajax发送的单个设置
	 */
	public function ajaxSet (Request $request)
	{
		//实例化模型
		$Model = new Setting();

		//表单验证
		$Model->setOneValidator($request->all());

		//更新数据库
		$res = $Model->setOne($request->all());

		if ($res !== false) {
			//删除缓存
			Cache::forget('settingGroupList');
			return Tool::ajaxReturn(200, '更新成功');
		} else {
			return Tool::ajaxReturn(400, '更新失败');
		}
	}



	/*
	 * 展示品牌列表
	 * post提交过来为删除操作
	 */
	public function show (Request $request, $field = 'id', $order = 'asc')
	{
		$Model = new Setting();

		//检测是否有缓存
		if (Cache::has('settingGroupRow')) {
			$settingGroupRow = Cache::get('settingGroupRow');
		} else {
			//获取配置分组
			$settingGroupRow = $Model->getSettingGroup();
			//生成缓存
			Cache::forever('settingGroupRow', $settingGroupRow);
		}

		if (Cache::has('settingGroupList')) {
			$settingGroupList = Cache::get('settingGroupList');
		} else {
			//获取配置项
			$settingList = $Model->getSetting();
			//遍历所有配置项分组管理
			$settingGroupList = array();
			foreach ($settingList as $setting) {
				$settingGroupList[$setting['setting_group_id']][] = $setting;
			}
			//生成缓存
			Cache::forever('settingGroupList', $settingGroupList);
		}


		//处理页面class和url问题
		$list = Tool::sortClass($field, $order);

		$list['settingGroupRow'] = $settingGroupRow;
		$list['settingGroupList'] = $settingGroupList;

		return view('back.setting.list', $list);

	}
}
